package ass2;

public class Environment {

	private static Agent Predator;
	private static Agent Prey;
	int BoardSize = 11;
	int MaximumTurns;
	float preyMoveProb = (float) 0.2;
	float alpha, gamma, epsilon;
	

    public Environment(int maxTurns, int boardSize, float Alpha, float Gamma, float Epsilon) {
			MaximumTurns = maxTurns;
			BoardSize = boardSize;
			alpha = Alpha;
			gamma = Gamma;
			epsilon = Epsilon;
    }

   
	public int playGame(Gui gui) {
		int turns = 0;
		boolean preyCaught = false;
		while( !preyCaught )
		{
			preyCaught = movePredator();
			if(preyCaught) 
				break;
			movePrey();
			turns++;
			if(turns > MaximumTurns && MaximumTurns  > 0)
				return -1;
			if(gui.Enabled) {
				gui.repaint();
				try {
					Thread.sleep(gui.stoptime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		((ass2.Predator) Predator).finishEpisode();
		return turns;
	}

	public void spawnPredator(Location spawn, String algorithm) {
		Predator = new Predator(spawn, this, alpha, gamma, epsilon, algorithm);
		
	}

	public void spawnPrey(Location spawn) {
		Prey = new Prey(spawn, this);
	}

	public void reset()
	{
		Predator.setLocation(new Location(0,0));
		Prey.setLocation(new Location(5,5));
	}

	public boolean movePredator() {
		Predator.move();
		int reward = getReward();
		if(reward > 0 )
				return true;
		return false;
	}

	public void movePrey() {
		Prey.move();
	}

	public static Predator getPredator() {
		return (ass2.Predator) Predator;
	}

	public static Agent getPrey() {
		return Prey;
	}
	/**
	 * Check if the predator caught the prey
	 */
	int getReward() {		
		if(getState().x == 5 && getState().y == 5) {
			return 10;}
		return 0;
	}
	State getState() {
		
		Location preyLocation = Prey.getLocation();
		Location predatorLocation = Predator.getLocation();
		//System.out.println(preyLocation.toString() + " " + getLocation().toString());
		Location preyDiff = Tools.subLocs(preyLocation, new Location(5,5));
		Location newPredatorLocation = Tools.mod(Tools.subLocs(predatorLocation, preyDiff), BoardSize);
		State state = new State(newPredatorLocation.x, newPredatorLocation.y);
		//System.out.println("Locations: " + predatorLocation.toString() + " " + preyLocation.toString() + " State: " + state);
		
		return state;
	}
}
